package top.luo.sqlSession;

import top.luo.config.BoundSql;
import top.luo.pojo.Configuration;
import top.luo.pojo.MappedStatement;
import top.luo.utils.GenericTokenParser;
import top.luo.utils.ParameterMapping;
import top.luo.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author luo
 * @date 2021-01-04 21:58
 */
public class SimpleExecutor implements Executor {

    @Override
    @SuppressWarnings("unchecked")
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 声明驱动，获取链接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取 sql
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取预处理对象，preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4. 设置参数
        // 获取参数的全路径
        Class<?> parameterClazz = getClassType(mappedStatement.getParameterType());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        ParameterMapping parameterMapping;
        Field declaredField;
        for (int i = 0; i < parameterMappings.size(); i++) {
            parameterMapping = parameterMappings.get(i);
            // 反射回去实体参数属性值
            declaredField = parameterClazz.getDeclaredField(parameterMapping.getContent());
            // 设置可访问
            declaredField.setAccessible(true);
            // 参数设置
            preparedStatement.setObject(i + 1, declaredField.get(params[0]));
        }

        // 5. 执行 sql
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6. 封装返回结果集
        String resultType = mappedStatement.getResultType();
        Class<?> resultClazz = getClassType(resultType);
        List<Object> resultList = new ArrayList<>();

        Object result;
        ResultSetMetaData metaData;
        while (resultSet.next()) {
            // 元数据（可获取到字段名称）
            metaData = resultSet.getMetaData();

            result = resultClazz.newInstance();

            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClazz);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(result, value);

            }
            resultList.add(result);
        }

        return (List<E>) resultList;
    }

    /**
     * 解析sql
     * <p>
     * 1. 将 #{} 用 ? 代替
     * 2. 解析 #{} 的值
     */
    private BoundSql getBoundSql(String sql) {
        // 处理占位符
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser parser = new GenericTokenParser("#{", "}", tokenHandler);
        // 解析后的sql
        String parsedSql = parser.parse(sql);
        // 参数名称(#{id} 中的 id, 实体类的属性名称)
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        return new BoundSql(parsedSql, parameterMappings);
    }


    private Class<?> getClassType(String classType) throws ClassNotFoundException {
        if (classType != null) {
            return Class.forName(classType);
        }
        return null;
    }

}
